package com.example.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Component
public class WeChatUtil {

    public static final String URL = "https://api.weixin.qq.com/sns/jscode2session";
    public static final String AUTHORIZATION = "authorization_code";

    @Value("${wechat.appid}")
    private String appid; //小程序的appid
    @Value("${wechat.secret}")
    private String secret; //小程序的秘钥
    @Value("${wechat.mchid}")
    private String mchid; //商户号
    @Value("${wechat.mchSerialNo}")
    private String mchSerialNo; //商户API证书的证书序列号
    @Value("${wechat.privateKeyFilePath}")
    private String privateKeyFilePath; //商户私钥文件
    @Value("${wechat.apiV3Key}")
    private String apiV3Key; //证书解密的密钥
    @Value("${wechat.weChatPayCertFilePath}")
    private String weChatPayCertFilePath; //平台证书
    @Value("${wechat.notifyUrl}")
    private String notifyUrl; //支付成功的回调地址
    @Value("${wechat.refundNotifyUrl}")
    private String refundNotifyUrl; //退款成功的回调地址

    public String getOpenId(String code) {
        HashMap<String, Object> query = new HashMap<>();
        query.put("appid", appid);
        query.put("secret", secret);
        query.put("js_code", code);
        query.put("grant_type", AUTHORIZATION);
        // 发送 GET 请求并携带查询参数
        String body = HttpUtil.get(URL, query);
        //解析body
        Map<String, Object> result = JSONUtil.parseObj(body);
        String openid = (String) result.get("openid");
        return openid;
    }
}